package self.seon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import self.seon.domain.LoginUser;
import self.seon.domain.User;
import self.seon.mapper.DoorMapper;
import self.seon.mapper.MenuMapper;

import java.util.List;
import java.util.Objects;

/**
 * @author Seon
 * @date 2022/8/30 16:47
 */
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private DoorMapper doorMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("nick_name", username);
        User user = doorMapper.selectOne(wrapper);

        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或者密码错误");
        }
        // 封装权限信息
        Long userId = user.getId();
        List<String> authority = menuMapper.selectPermsByUserId(userId);
//        List<String> authority = Arrays.asList("user", "admin", "super-admin");
        // 把数据封装成UserDetail返回
        return new LoginUser(user, authority);
    }
}